﻿using System;
using System.Collections.Generic;

using WAF.EntityFramework;
using TradeClient.Logic.TradeCore;

namespace TradeClient.Logic.Entity
{
    public partial class Position
    {
        /// <summary>
        /// 详细持仓
        /// </summary>
        private List<PositionDetail> positionDetails;

        private Position()
        { 
            
        }

        public string GetKey()
        { 
            
        }

        /// <summary>
        /// 开仓
        /// </summary>
        /// <param name="tradeTime">交易时间</param>
        /// <param name="price">开仓价格</param>
        /// <param name="volume">开仓数量</param>
        public void Open(DateTime tradeTime, double price, int volume)
        {
            //结果采取四舍六入法，保留两位小数
            this.Price = Math.Round((this.Price * this.Volume + price * volume) / (this.Volume + volume), 2);

            this.Volume += volume;

            PositionDetail detail = new PositionDetail();
            detail.PositionId   = this.Id;
            detail.Price        = price;
            detail.Volume       = volume;
            detail.OpenDateTime = tradeTime.ToString("yyyy-MM-dd hh:mm:ss");

            UpdateToDb();
        }

        /// <summary>
        /// 平仓
        /// </summary>
        /// <param name="tradeTime">交易时间</param>
        /// <param name="price">平仓价格</param>
        /// <param name="volume">平仓数量</param>
        public void Close(DateTime tradeTime, double price, int volume)
        {
            //结果采取四舍六入法，保留两位小数
            this.Price = Math.Round((this.Price * this.Volume - price * volume) / (this.Volume - volume), 2);

            this.Volume -= volume;

            DateTime lastTime = DateTime.MinValue;

            foreach (PositionDetail detail in positionDetails)
            {
                DateTime positionTime = DateTime.Parse(detail.OpenDateTime);

                if (lastTime.CompareTo(positionTime) < 0)
                    lastTime = positionTime;
            }

            UpdateToDb();

            //如果已经全部平仓则清除持仓记录
            if (this.Volume == 0)
            {
                PositionManager.GetInstance().Remove(this);
                EntityAction.Delete(this.positionRecord);
            }
        }


        /******************************** private ********************************/

        /// <summary>
        /// 更新数据库中的持仓记录
        /// </summary>
        private void UpdateToDb()
        {
            this.positionRecord.Volume = this.Volume;
            this.positionRecord.Price = this.Price;

            EntityAction.Update(this.positionRecord);
        }
    }
}
